package com.example.vote.springboot_vote.controller;

import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping(path = "/files")
@RestController
public class FileController {
    /**
     * # 设备截图文件保存路径(文件存在具体的文件夹的路径)
     * smas.captrue.image.path=home/capture/
     */
    @Value("${smas.captrue.image.path}")
    private String captureImagePath;
    /**
     * #文件上传后存储路径：D:\home\capture\5\*.jpg(具体配置如下)
     * #访问Url:http://ip:port/smas/upload/*
     * #文件上传目录(window是d/e/f盘， linux是/)（注意Linux和Windows上的目录结构不同）
     * #file.uploadFolder=/
     * file.uploadFolder=d://
     */
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    /**
     * #浏览器访问
     * file.uri=/upload/
     */
    @Value("${file.uri}")
    private String uri;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/vupload", method = RequestMethod.POST)
    public String vUploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws FileNotFoundException {
        String UPLOAD_FILE_PATH  = uploadFolder + captureImagePath;
        if (!file.isEmpty()) {
            Map<String, String> resObj = new HashMap<>();
            try {
                File fTemp = new File(UPLOAD_FILE_PATH);
                if (!fTemp.exists()) {
                    fTemp.mkdirs();
                }
                File resFile = new File(UPLOAD_FILE_PATH, file.getOriginalFilename());
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(resFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
                        url += File.separator + uri + resFile.getName();
                resObj.put("filePath",url);
            } catch (IOException e) {
                resObj.put("msg", "error");
                resObj.put("code", "1");

//                return JSONObject.toJSONString(resObj);
            }
            resObj.put("msg", "ok");
            resObj.put("code", "0");
            return JSONObject.toJSONString(resObj);
        } else {
            return null;
        }
    }

    /**
     * 下载测试
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/vdownload")
    @ResponseBody
    private void downloadFile(@RequestParam("fileName") String fileName) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        String UPLOAD_FILE_PATH  = uploadFolder + captureImagePath;
        File file = new File(UPLOAD_FILE_PATH+File.separator+fileName);
        if (file.exists()) {
            // 设置信息给客户端不解析
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type",type);
            // 设置编码
            fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
            // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setContentType("application/force-download");// 设置强制下载不打开            
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            // 发送给客户端的数据
            OutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            // 读取filename
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                i = bis.read(buff);
            }
        }
        System.out.println("下载方法完毕");
    }
}
